#!/bin/ksh
#
# $Id$
#

args=$@

usage() {
    echo "Usage: `basename $0` [-t] [-z] [-f <input file>] -h <host>"
    echo -e "\t-z\tuse gzip for compressing"
    echo -e "\t-t\ttest, not copy files"
    echo -e "\t-f <input file>\t default: input/mbackup.list"	
}

gzip_flag=0
test_flag=0
host=
filelist=

# {{{ parsing positional parameter
while [ $# -gt 0 ]; do
    case "$1" in
        -h) [ -z "$2" ] && { usage; exit 1; }
            host=`echo $2 | awk '{print $1}'`
            shift
            ;;
        -f) [ -z "$2" ] && { usage; exit 1; }
            filelist=$2
            [ ! -f "$filelist" ] && { echo "file $filelist not found. exit 1"; exit 1; }
            shift
            ;;
	-t) test_flag=1
    	    ;;
	-z) gzip_flag=1
	    ;;
	*)  echo "unknown option \"$1\""
	    usage
    	    exit 1	    
    esac
    shift
done
# }}}

[ -z "$host" ] && { usage; exit 1; }
mkdir -p input output logs

[ -z "$filelist" ] && filelist=input/`basename $0 .sh`.list
[ ! -f "$filelist" ] && { echo "filelist \"$filelist\" not found"; exit 1; }
[ ! -f mbackup.local.sh ] && { echo "file \"mbackup.local.sh\" not found"; exit 1; }

logfile=logs/`basename $0 .sh`.$host.log; mkdir -p logs
echo "-------------------------------"  > $logfile
echo "$0 $args"                         >> $logfile
echo "-------------------------------"  >> $logfile

if [ "$test_flag" = 1 ]; then 
    # {{{ test, not copy files 
	source_commands=`cat $filelist | sed -e '/./{H;$!d;}' -e 'x;/\[commands\]/!d;' | egrep -v "\[commands\]|^$|^#"`
	source_files=`cat $filelist | sed -e '/./{H;$!d;}' -e 'x;/\[files\]/!d;' | egrep -v "\[files\]|^$|^#"`

    command="for i in \`echo \"$source_files\"\`
		do
		    du -skL \$i
		done
	     for i in \`echo \"$source_commands\" | sed s/\ /\|/g\`
	        do
		    echo \$i | sed s/\|/\ /g
		done"    

    ssh $host "$command" >>$logfile
    cat $logfile | awk 'BEGIN {s=0} {s=s+$1} END {print "total size: " s " KB"}'
    # }}}
else
    # {{{ get files  

    # {{{ put scripts to host 
    echo "put scripts to $host ..."    
    sftp $host >>$logfile 2>&1 << END
put $filelist
put mbackup.local.sh
END
    # }}}

    # {{{ collect files 
    echo "collect files on $host ..."
    param=""
    suffix="tar"
    if [ $gzip_flag -eq 1 ]; then
	param="-z"
	suffix="tar.gz"    
    fi
    filelist_name=`basename $filelist`
    backup_dir=`basename $0 .sh`.$host
    ssh $host "./mbackup.local.sh $param $filelist_name $backup_dir" >>$logfile
    echo "get archive from $host ..."    
    # }}}

    # {{{ get files from host
    sftp $host >>$logfile 2>&1 << END
get $backup_dir.$suffix
rm $backup_dir.$suffix
rm $filelist_name*
rm mbackup.local.sh
END
    mv $backup_dir.$suffix output/
    # }}}
    # }}}z
fi

echo "FINISH"
echo "details into $logfile"
